<?php
/**
 * 收钱吧退款接口
 */

namespace App\Services\PosApi;

use App\Jobs\RefundQueryJob;
use App\Models\RefundDetail as RefundDetailModel;
use App\Services\PosApi\ShouQianBa\Operations\RefundOperation;
use App\Services\PosApi\ShouQianBa\Operations\RefundQueryOperation;
use D1M\Payment\ShouQianBa\ClientInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ShouqianbaRefund
{
    public $paymentName = '收钱吧';
    public $paymentCode = 'shouqianba';

    public function handle($params, $payInfo, $refund_amount)
    {
        $refund = RefundDetailModel::where('order_no', $params['order_no'])->where('refund_no', $params['refund_no'])->where('refund_platform', $this->paymentCode)->first();
        if (!$refund) {
            $refund = new RefundDetailModel();
            $refund->refunds_id = $params['refunds_id'];
            $refund->order_no = $params['order_no'];
            $refund->refund_no = $params['refund_no'];
            $refund->refund_amount = $refund_amount;
            $refund->refund_platform = $this->paymentCode;

            $refund->save();
        }

        $result = $this->sendRefunds($params, $payInfo, $refund_amount,$refund->id);

        //更新支付状态,只更新失败的，成功的由通知接口或者定时查询接口更新
        if ($result['code'] === 1) {
            $refund->status = 2;
            $refund->fail_memo = $result['msg'];//失败原因;
            $refund->save();
        }else{
            $jobData = [
                'id'=>$refund->id,
                'store_sn'=>$payInfo['store_sn']
            ];
            //异步调收钱吧查询接口
            RefundQueryJob::dispatch($jobData)->delay(now()->addSeconds(5));
        }

        return $refund->toArray();


    }

    public function sendRefunds($params, $payInfo, $refund_amount,$refundDetailId)
    {
        $tenders = [];
        $amount = 0 - $refund_amount;
        foreach ($payInfo['tenders'] as $tender){
            if($refund_amount>0){
                if($tender['amount']>=$refund_amount){
                    $tenderAmount = (0-$refund_amount);
                    $refund_amount = 0;
                }else{
                    $tenderAmount = (0-$tender['amount']);
                    $refund_amount -= $tender['amount'];
                }
                $tenders[] = [
                    'transaction_sn' => $params['refund_no'].'-'.$tender['id'],
                    'amount' => $tenderAmount,//退款金额，精确到分，退款为负
                    'pay_status' => '0',
                    'original_tender_sn' => $tender['tender_sn'],//订单支付流水
                ];
            }
        }
        $shouqianbaSetting = DB::table('pos_payment.shouqianba_settings')
            ->where('shop_bn','=',$payInfo['store_sn'])
            ->where('status','=',1)
            ->first();
        $body = [
            "request_id" => md5(time() . rand(100, 999)),    //请求编号，每次请求必须唯一
            "brand_code" => $shouqianbaSetting->brand_code,            //品牌编号，系统对接前由“收钱吧”提供
            "store_sn" => $payInfo['store_sn'],                 // 商户门店编号
            "workstation_sn" => "0",                 //门店收银机编号，如果没有请传入“0”
            "check_sn" => $params['refund_no'],          //商户退货款号，在商户系统中唯一
            //"sales_sn" => $params['order_no'],          //POS或电商等业务系统内的退货订单号（会显示我方出具的对账单中，方便对账。并不作为交易依据）
            "sales_time" => date('c'),                 //订单创建时间
            "amount" => $amount,                   //订单价格，精确到分
            "currency" => "156",                 //币种， 如：”156”for CNY
            "subject" => "refund",                //订单主题
            "operator" => $payInfo['operator'],                 //操作员，例如“张三“
            //"customer" => "",                 //客户信息，可以是客户姓名或会员号
            "industry_code" => "0",            //行业代码, 0=零售1:酒店; 2:餐饮; 3:文娱; 4:教育;
            "pos_info" => config('app.name'),            //本接口对接的对端的信息
            "notify_url" => route('refund-notifications', ['id' => $refundDetailId]),//通知接收地址
            "tenders" => $tenders
        ];

        // 请求收钱吧
        $operation = new RefundOperation($body);
        $result = app()->get(ClientInterface::class)->request($operation);

        if ($result->hasError()) {
            $error_message = $result->getErrorMessage();
            return ['code' => 1, 'msg' => $error_message];
        } else {
            return ['code' => 0];
        }
    }

    public function query($params,$payInfo)
    {
        $shouqianbaSetting = DB::table('pos_payment.shouqianba_settings')
            ->where('shop_bn','=',$payInfo['store_sn'])
            ->where('status','=',1)
            ->first();
        $body = [
            "brand_code" => $shouqianbaSetting->brand_code,            //品牌编号，系统对接前由“收钱吧”提供
            "store_sn" => $payInfo['store_sn'],                 // 商户门店编号
            "workstation_sn" => "0",                 //门店收银机编号，如果没有请传入“0”
            "check_sn" => $params['refund_no'],          //商户退货款号，在商户系统中唯一
            //"order_sn"=>'7903247757290265',
        ];

        // 请求收钱吧
        $operation = new RefundQueryOperation($body);
        Log::info('退款查询body:' . var_export($operation->getRequestBody(), 1));
        $result = app()->get(ClientInterface::class)->request($operation);
        Log::info('退款查询result:' . var_export($result, 1));
        if ($result->hasError()) {

        }else{
            $data = $result->getData();
            if($data['order_type']=='2' && $data['order_status']=='4'){
                return $data;
            }
        }
        return false;
    }
}